import React, { FC, useEffect, useState } from 'react'
import type { ChangeEvent } from 'react'
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom'
import { Input } from 'antd'
import { LIST_SEARCH_PARAM_KEY } from '../constant'
const { Search } = Input

const ListSearch: FC = () => {
    const nav = useNavigate()
    const { pathname } = useLocation()
    const [value, setValue] = useState('')
    function handleChange(event: ChangeEvent<HTMLInputElement>) {
        setValue(event.target.value)
    }
    // 搜索触发会改变URL，获取URL的参数，以防止搜索框内容被清空
    const [searchParams] = useSearchParams()
    useEffect(() => {
        const currentVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
        setValue(currentVal)
    }, [searchParams])
    function handleSearch(value: string) {
        // 改变URL，以保证刷新时不丢失搜索数据
        nav({
            pathname,
            search: `${LIST_SEARCH_PARAM_KEY}=${value}`,
        })
    }
    return (
        <>
            <Search
                placeholder="输入关键字"
                allowClear
                value={value}
                onSearch={handleSearch}
                onChange={handleChange}
                style={{ width: '300px' }}
            />
        </>
    )
}

export default ListSearch
